package bam.cobol.converter;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;

public class SourceFilter {
	public static String encoding = "MS932";
	
	public static Reader CobolInputStream( String file )
	{
		Reader result = null;
		StringBuffer sb = new StringBuffer();
		String lineSeparator = System.getProperty("line.separator");
		
		try
		{
			 InputStreamReader sr = new InputStreamReader(new FileInputStream(file), encoding );
			 BufferedReader br = new BufferedReader(sr);
			 String line = null;
			 while ((line = br.readLine()) != null) 
			 {
				 byte[] bytes = line.getBytes();  
				 if (bytes.length > 72)
				 {
					 line = new String(bytes, 0, 72);  
				 }
				 sb.append(line).append(lineSeparator);
			 }
			 br.close();
			 sr.close();
			 //delete the LF/CR at EOF
			 sb.setLength(sb.length() - lineSeparator.length());
			 //tmp start
			 
			 Writer wr = new OutputStreamWriter(new FileOutputStream(file + ".tmp"));  
			 wr.write(sb.toString());
			 wr.close();
			 
			 result = new BufferedReader(new StringReader(sb.toString()));
		} 
		catch ( Exception e )
		{
			System.out.println(e.getMessage());
		}
		return result;
	}
	
	/*
	public static void main(String[] args) {
		SourceFilter.SourceInputStream("kanji.txt");
		System.out.println("Done.");
	}
	*/
}
